package org.dream.service;

import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.dream.util.DateUtil;
import org.dream.util.PropUtil;

public class StockDayServiceImpl implements StockDayService {
	private static Set<String> closeDays;
	static {
		closeDays = new HashSet<String>();
		for (int year = 1990; year < 2020; year++) {
			String str = PropUtil.getProperty("" + year);
			if(null==str||str.equals("")){
				continue;
			}
			for (String day : str.split(",")) {
				if (day.split("-").length == 1) {
					closeDays.add(year + "/" + day);
				} else {
					String pre = day.split("-")[0].substring(0, 3);
					int start = Integer.parseInt(day.split("-")[0].substring(3, 5));
					int end = Integer.parseInt(day.split("-")[1]);
					for (int i = start; i <= end; i++) {
						closeDays.add(year + "/" + pre + (i < 10 ? "0" + i : i));
					}
				}

			}
		}

	}

	public boolean isOpen(String day) {
		// 除去周末和假期，就是开市的
		if (DateUtil.isWeekDay(day)) {
			return false;
		} else if (closeDays.contains(day)) {
			return false;
		} else {
			return true;
		}
	}

	public String getMonthFirstOpenDay(String dayStr) {
		Date date = DateUtil.getDate(dayStr);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		Date reDate = calendar.getTime();
		while (!this.isOpen(DateUtil.getDateStr(reDate))) {
			calendar.add(calendar.DAY_OF_MONTH, 1);
			reDate = calendar.getTime();
		}
		return DateUtil.getDateStr(reDate);
	}

	public boolean isMonthFirstOpenDay(String dayStr) {
		String monthFirstOpenDay = getMonthFirstOpenDay(dayStr);
		return monthFirstOpenDay.equals(dayStr);
	}
}
